package br.com.amadeus.android.activities.home;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import br.com.amadeus.android.business.FacadeAmadeusDroid;
import br.com.amadeus.android.entities.Config;
import br.com.amadeus.android.entities.Course;
import br.com.amadeus.android.entities.CourseUser;
import br.com.amadeus.android.entities.SocialHistory;
import br.com.amadeus.android.historic.AmadeusDroidHistoric;
import br.com.amadeus.android.util.ConstantsAmadeusDroid;
import br.com.amadeus.android.util.JSONReader;
import br.com.amadeus.android.util.PendingIntentService;
import br.com.amadeus.android.util.PreferencesNotificationService;
import br.com.amadeus.android.util.RESTFileContent;
import br.com.amadeus.android.util.SchedulerSyncronize;

public class MainActivity extends Activity{


	// 2 segundos
	private final int DELAY = 2000;
	private static final int FECHAR_SPLASH = 1;

	FacadeAmadeusDroid facade = null;
	SharedPreferences getPrefs = null;
	protected static final String CATEGORIA = "curso";
	private static final int SAIR = 0;
	boolean fistSync;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.splash_amadeus);

		this.facade = FacadeAmadeusDroid.getInstance(this);

		getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

		String newFolder = "/amadeus-droid/arquivos/acessibilidade";
		String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
		File myNewFolder = new File(extStorageDirectory + newFolder);
		myNewFolder.mkdirs();

		Message msg = new Message();
		msg.what = FECHAR_SPLASH;
		handler.sendMessageDelayed(msg, DELAY);

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		finish();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case FECHAR_SPLASH:

				int opcao = Integer.parseInt(getPrefs.getString("listPref", "1"));

				switch (opcao) {
				case ConstantsAmadeusDroid.MODO_ONLINE:

					fistSync = facade.firstSyncronizing();
					if (fistSync) {		
						Intent openStartingPoint = new Intent("FIRST_INNER");
						startActivity(openStartingPoint);
					}else{

						Config config = facade.getConfig();
						String url = config.getAmadeus_url() + ConstantsAmadeusDroid.HOST_AMADEUS_WEB +
						"/" + config.getUser_login() + "/" + config.getUser_password();
						RESTFileContent rfc = new RESTFileContent();
						try {
							boolean testHost = false;

							testHost = RESTFileContent.testHostValidation(url);
							if (testHost) {
								InputStream is = rfc.getRESTFileContent(url);
								String courses = rfc.toString(is);

								rfc = new RESTFileContent();
								String url2 = url.replace("service", "countcourses");
								InputStream is2 = rfc.getRESTFileContent(url2);
								String count = rfc.toString(is2);
								int countCourses = JSONReader.countCourses(count);

								ArrayList<Course> listCourses = JSONReader.getListCourses(courses, countCourses);
								ArrayList<CourseUser> listCourseUser = JSONReader.getListCourseUser(courses);

								String url3 = config.getAmadeus_url() + 
								ConstantsAmadeusDroid.HOST_AMADEUS_WEB_HISTORY;
								rfc = new RESTFileContent();
								InputStream is3 = rfc.getRESTFileContent(url3);
								String historic = rfc.toString(is3);
								ArrayList<SocialHistory> listSocial = JSONReader.getAmadeusHistoric(historic);

								facade.syncronizeAmadeus(listCourses, listCourseUser, null, listSocial);
								Intent it = new Intent("HOME");
								startActivity(it);
							}else{
								//Usuário sem conexão

								SharedPreferences.Editor editor = getPrefs.edit();
								editor.putString("listPref", Integer.toString(ConstantsAmadeusDroid.MODO_OFFLINE));
								editor.commit();

								Intent it = new Intent("HOME");
								startActivity(it);
							}

						} catch (ClientProtocolException e) {
							Log.e(CATEGORIA, e.getMessage(), e);
						} catch (JSONException e) {
							Log.e(CATEGORIA, e.getMessage(), e);
						} catch (UnknownHostException e){	

							//Usuário sem conexão

							SharedPreferences.Editor editor = getPrefs.edit();
							editor.putString("listPref", Integer.toString(ConstantsAmadeusDroid.MODO_OFFLINE));
							editor.commit();

							Intent it = new Intent("HOME");
							startActivity(it);

						} catch (ParseException e) {
							Log.e(CATEGORIA, e.getMessage(), e);
						} catch (IOException e) {
							Log.e(CATEGORIA, e.getMessage(), e);
						}

					}

					break;

				case ConstantsAmadeusDroid.MODO_OFFLINE:

					Intent it = new Intent("HOME");
					startActivity(it);

					break;
				}

				break;
			}
		}

	};


}
